package com.kevin.springcloud.controller;

import com.kevin.springcloud.entities.CommonResult;
import com.kevin.springcloud.entities.Payment;
import com.kevin.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author xijinlong
 * @date 2020-08-22 20:21
 */
@RestController
@Slf4j
public class PaymentController {


    @Value("${server.port}")
    String serverPort;

    @Autowired
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;


    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        boolean save = paymentService.save( payment);
        if (save) {
            return new CommonResult(200, "插入成功,serverPort:"+serverPort);
        } else {
            return new CommonResult(500, "插入失败,serverPort:"+serverPort);

        }

    }


    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        log.info(serverPort);
        Payment payment = paymentService.getById(id);
        if (payment!=null){
            return new CommonResult(200, "查询成功,serverPort:"+serverPort, payment);
        }
         return new CommonResult(500, "没有记录,serverPort:"+serverPort);

    }

    @GetMapping("/payment/discovery")
    public DiscoveryClient discovery(){

        // 得到所有服务名
        List<String> services = discoveryClient.getServices();
        services.forEach(ele->{
            log.info("***service***" + ele);
        });
        // 得到服务名对应的信息
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        instances.forEach(ele->{
            log.info(ele.getServiceId()+"\t"+ele.getHost()+"\t"+ele.getPort()+"\t"+ele.getUri());
        });

        return discoveryClient;

    }


}
